package com.elm.interceptor;

import com.elm.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取Token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(401); // 未提供Token
            return false;
        }

        try {
            // 验证Token并解析用户信息
            JwtUtil.parseToken(token);
            // 将Token存入请求属性，供后续使用
            request.setAttribute("token", token);
            return true;
        } catch (Exception e) {
            response.setStatus(401); // Token无效或过期
            return false;
        }
    }
}